package com.demo.app.util;

import com.alibaba.fastjson.JSON;
import com.demo.app.common.Result;
import org.apache.commons.lang.StringEscapeUtils;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 * 回写JSON 工具类
 * </p>
 *
 * @author zhangxt
 * @date 2023/11/1
 */
public class ResponseJsonUtil {

    /**
     * 处理字符串类型
     *
     * @param response
     * @param json
     */
    public static void writeJSON(ServletResponse response, String json) {
        try {
            response.setContentType("application/json; charset=UTF-8");
            writeJSON(response.getWriter(), json);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 处理 ResultEntity 类型
     *
     * @param response
     * @param resultEntity
     */
    public static void writeJSON(ServletResponse response, Result resultEntity) {
        try {
            response.setContentType("application/json; charset=UTF-8");
            writeJSON(response.getWriter(), resultEntity);
        } catch (IOException var3) {
            var3.printStackTrace();
        }

    }

    public static void writeJSON(PrintWriter writer, Result resultBean) {
        writer.print(StringEscapeUtils.unescapeJava(JSON.toJSONString(resultBean)));
        writer.flush();
        writer.close();
    }

    public static void writeJSON(PrintWriter writer, String json) {
        writer.print(json);
        writer.flush();
        writer.close();
    }

}
